from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
import os
from dotenv import load_dotenv
import json
import requests
import time
from datetime import datetime
import uuid
import base64
from urllib.parse import urlparse
import io
from PIL import Image

# 加载环境变量
load_dotenv()

app = Flask(__name__)
CORS(app)

# 配置API密钥
TONGYI_API_KEY = os.getenv('TONGYI_API_KEY') or "sk-4435f0d91c38492680e6d3bd4be8ec59"
TONGYI_SECRET_KEY = os.getenv('TONGYI_SECRET_KEY') or "lM0oxRFdbQ9vuTlMTRLnWNgrNfyNMVap"

# 配置选项 - 移除本地图片生成选项

# 创建图片保存目录
IMAGES_DIR = "static/images"
if not os.path.exists(IMAGES_DIR):
    os.makedirs(IMAGES_DIR)

class NovelToComicConverter:
    def __init__(self):
        self.tongyi_api_key = TONGYI_API_KEY
        self.tongyi_secret_key = TONGYI_SECRET_KEY
        
    def parse_novel_text(self, text, style="日系", target_scene="通用", panel_count=4):
        """
        使用通义千问解析小说文本，提取情节和人物信息
        """
        prompt = f"""
        请分析以下小说文本，提取关键信息并生成漫画分镜：
        
        小说文本：{text}
        
        要求：
        1. 提取主要人物及其特征（外貌、服饰、性格）
        2. 识别关键情节和场景
        3. 将内容分解为{panel_count}个分镜
        4. 为每个分镜生成详细的画面描述
        5. 画风：{style}
        6. 目标场景：{target_scene}
        
        请以JSON格式返回结果：
        {{
            "characters": [
                {{"name": "角色名", "description": "外貌特征描述"}}
            ],
            "panels": [
                {{"panel_id": 1, "scene": "场景描述", "action": "动作描述", "visual_prompt": "画面生成提示词"}}
            ]
        }}
        """
        
        # 调用通义千问API - 使用DashScope API
        headers = {
            'Authorization': f'Bearer {self.tongyi_api_key}',
            'Content-Type': 'application/json'
        }
        
        data = {
            "model": "qwen-turbo",
            "input": {
                "prompt": prompt
            },
            "parameters": {
                "temperature": 0.7
            }
        }
        
        try:
            response = requests.post(
                'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
                headers=headers,
                json=data,
                timeout=30
            )
            
            if response.status_code == 200:
                result = response.json()
                if 'output' in result and 'text' in result['output']:
                    return result['output']['text']
                else:
                    return {"error": "通义千问API返回格式异常"}
            else:
                return {"error": f"通义千问API调用失败: {response.status_code} - {response.text}"}
                
        except Exception as e:
            return {"error": f"通义千问API调用异常: {str(e)}"}
    
    
    def generate_comic_panel(self, visual_prompt, style="日系", character_descriptions="", panel_id=None):
        """
        生成漫画分镜（仅图片生成，不生成文字描述）
        """
        # 构建完整的提示词
        full_prompt = f"{visual_prompt}, {style}漫画风格, {character_descriptions}, 高质量, 清晰"
        
        # 直接生成图片，不生成文字描述
        image_result = self.generate_panel_image(full_prompt, style)
        
        # 如果图片生成失败，直接返回失败
        if not image_result.get("success"):
            return {
                "success": False,
                "error": f"图片生成失败: {image_result.get('error')}",
                "visual_prompt": full_prompt
            }
        
        result = {
            "success": True,
            "visual_prompt": full_prompt,
            "image_url": image_result.get("image_url"),
            "image_data": image_result.get("image_data")
        }
        
        # 如果图片生成成功，尝试下载和保存
        if image_result.get("image_url") and panel_id:
            print(f"开始下载和保存分镜 {panel_id} 的图片...")
            download_result = self.download_and_save_image(image_result.get("image_url"), panel_id)
            if download_result.get("success"):
                result["local_url"] = download_result.get("local_url")
                result["filename"] = download_result.get("filename")
                result["download_success"] = True
                print(f"分镜 {panel_id} 图片下载成功: {download_result.get('filename')}")
            else:
                result["download_error"] = download_result.get("error")
                print(f"分镜 {panel_id} 图片下载失败: {download_result.get('error')}")
        
        return result
    
    def get_panel_description(self, visual_prompt, style):
        """获取分镜文字描述"""
        prompt = f"""
        请为以下场景生成详细的漫画分镜描述：
        
        场景：{visual_prompt}
        
        要求：
        1. 生成详细的画面描述
        2. 包含人物表情、动作、环境细节
        3. 描述色彩和光影效果
        4. 适合{style}漫画风格
        5. 描述要生动有趣，适合制作漫画
        
        请生成一个完整的漫画分镜描述。
        """
        
        # 调用通义千问API
        headers = {
            'Authorization': f'Bearer {self.tongyi_api_key}',
            'Content-Type': 'application/json'
        }
        
        data = {
            "model": "qwen-turbo",
            "input": {
                "prompt": prompt
            },
            "parameters": {
                "temperature": 0.7
            }
        }
        
        try:
            response = requests.post(
                'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
                headers=headers,
                json=data,
                timeout=60
            )
            
            if response.status_code == 200:
                result = response.json()
                if 'output' in result and 'text' in result['output']:
                    return result['output']['text']
                else:
                    return "无法生成分镜描述"
            else:
                return f"描述生成失败: {response.status_code}"
                
        except Exception as e:
            return f"描述生成异常: {str(e)}"
    
    def generate_panel_image(self, visual_prompt, style):
        """生成分镜图片"""
        print(f"开始生成图片: {visual_prompt}")
        print(f"画风: {style}")
        
        # 直接使用通义千问的图像生成API
        try:
            result = self.generate_image_with_tongyi(visual_prompt, style)
            print(f"图片生成结果: {result}")
            
            if result.get("success"):
                print("图片生成成功！")
                return result
            else:
                print(f"图片生成失败: {result.get('error')}")
                # 直接返回失败，不提供备选方案
                return result
        except Exception as e:
            print(f"图片生成异常: {str(e)}")
            # 直接返回失败
            return {"success": False, "error": f"图片生成异常: {str(e)}"}
    
    def generate_image_with_tongyi(self, visual_prompt, style):
        """使用通义千问文生图模型生成图片"""
        # 构建图片生成提示词
        image_prompt = f"{visual_prompt}, {style}漫画风格, 高质量, 清晰, 动漫风格, 漫画分镜"
        
        print(f"使用通义千问文生图模型生成图片: {image_prompt}")
        
        try:
            # 直接使用通义千问的文生图API
            result = self.generate_image_with_tongyi_api(image_prompt, style)
            if result.get("success"):
                print("通义千问文生图模型成功生成图片")
                return result
            else:
                print(f"通义千问文生图模型失败: {result.get('error')}")
                # 直接返回失败，不尝试备选方案
                return result
        except Exception as e:
            print(f"通义千问文生图模型异常: {e}")
            # 直接返回失败
            return {"success": False, "error": f"通义千问文生图模型异常: {str(e)}"}
    
    def generate_image_with_tongyi_api(self, image_prompt, style):
        """使用通义千问文生图API"""
        try:
            # 使用通义千问的文生图API - 同步接口
            headers = {
                'Authorization': f'Bearer {self.tongyi_api_key}',
                'Content-Type': 'application/json'
            }
            
            data = {
                "model": "qwen-image-plus",  # 使用qwen-image-plus模型
                "input": {
                    "messages": [
                        {
                            "role": "user",
                            "content": [
                                {
                                    "text": f"{image_prompt}, {style}漫画风格, 高质量, 清晰"
                                }
                            ]
                        }
                    ]
                },
                "parameters": {
                    "negative_prompt": "",
                    "prompt_extend": True,
                    "watermark": False,
                    "size": "1328*1328"
                }
            }
            
            # 使用同步接口端点
            response = requests.post(
                'https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation',
                headers=headers,
                json=data,
                timeout=60
            )
            
            print(f"通义千问API响应状态: {response.status_code}")
            print(f"通义千问API响应内容: {response.text}")
            
            if response.status_code == 200:
                result = response.json()
                print(f"通义千问API响应: {json.dumps(result, ensure_ascii=False, indent=2)}")
                
                if 'output' in result and 'choices' in result['output']:
                    choices = result['output']['choices']
                    if len(choices) > 0 and 'message' in choices[0]:
                        message = choices[0]['message']
                        if 'content' in message and len(message['content']) > 0:
                            content = message['content'][0]
                            if 'image' in content:
                                image_url = content['image']
                                return {
                                    "success": True,
                                    "image_url": image_url,
                                    "source": "tongyi"
                                }
                            else:
                                return {"success": False, "error": "通义千问API返回格式异常：缺少图片URL"}
                        else:
                            return {"success": False, "error": "通义千问API返回格式异常：缺少内容"}
                    else:
                        return {"success": False, "error": "通义千问API返回格式异常：缺少选择结果"}
                else:
                    return {"success": False, "error": "通义千问API返回格式异常：缺少输出"}
            else:
                return {"success": False, "error": f"通义千问API调用失败: {response.status_code} - {response.text}"}
                
        except Exception as e:
            return {"success": False, "error": f"通义千问API异常: {str(e)}"}
    
    def download_and_save_image(self, image_url, panel_id):
        """下载并保存图片到本地"""
        try:
            print(f"开始下载图片: {image_url}")
            
            # 下载图片
            response = requests.get(image_url, timeout=30)
            if response.status_code == 200:
                # 生成文件名
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                filename = f"panel_{panel_id}_{timestamp}.png"
                filepath = os.path.join(IMAGES_DIR, filename)
                
                # 保存图片
                with open(filepath, 'wb') as f:
                    f.write(response.content)
                
                # 返回本地文件路径和URL
                local_url = f"/static/images/{filename}"
                return {
                    "success": True,
                    "local_path": filepath,
                    "local_url": local_url,
                    "filename": filename
                }
            else:
                return {"success": False, "error": f"下载图片失败: {response.status_code}"}
                
        except Exception as e:
            return {"success": False, "error": f"下载图片异常: {str(e)}"}
    
    def convert_image_to_base64(self, image_url):
        """将图片转换为base64格式"""
        try:
            response = requests.get(image_url, timeout=30)
            if response.status_code == 200:
                image_data = base64.b64encode(response.content).decode('utf-8')
                return {
                    "success": True,
                    "image_data": f"data:image/png;base64,{image_data}"
                }
            else:
                return {"success": False, "error": f"获取图片失败: {response.status_code}"}
        except Exception as e:
            return {"success": False, "error": f"转换图片异常: {str(e)}"}
    
    def generate_image_fallback(self, image_prompt, style):
        """备选图片生成方案"""
        # 尝试多个免费的AI图片生成服务
        apis = [
            ("Pollinations", self.generate_image_with_pollinations),  # 最稳定的免费API
            ("Hugging Face", self.generate_image_with_huggingface),
            ("Replicate", self.generate_image_with_replicate)
        ]
        
        for api_name, api_func in apis:
            try:
                print(f"尝试使用 {api_name} API...")
                result = api_func(image_prompt, style)
                if result.get("success"):
                    print(f"{api_name} API 成功生成图片")
                    return result
                else:
                    print(f"{api_name} API 失败: {result.get('error')}")
            except Exception as e:
                print(f"{api_name} API 异常: {e}")
                continue
        
        # 如果所有API都失败，返回指导信息
        print("所有图片生成API都失败了，返回指导信息")
        return self.generate_image_placeholder(image_prompt, style)
    
    def generate_image_with_huggingface(self, image_prompt, style):
        """使用Hugging Face免费API生成图片"""
        try:
            # 使用Hugging Face的免费Stable Diffusion API
            # 注意：免费API不需要token，但可能有速率限制
            url = "https://api-inference.huggingface.co/models/runwayml/stable-diffusion-v1-5"
            
            headers = {
                "Content-Type": "application/json"
            }
            
            data = {
                "inputs": image_prompt,
                "parameters": {
                    "num_inference_steps": 20,
                    "guidance_scale": 7.5
                }
            }
            
            # 减少超时时间，避免长时间等待
            response = requests.post(url, headers=headers, json=data, timeout=30)
            
            if response.status_code == 200:
                # 返回图片数据
                import base64
                image_data = base64.b64encode(response.content).decode('utf-8')
                return {
                    "success": True,
                    "image_data": f"data:image/png;base64,{image_data}"
                }
            elif response.status_code == 503:
                # 模型正在加载中
                return {"success": False, "error": "Hugging Face模型正在加载中，请稍后重试"}
            else:
                return {"success": False, "error": f"Hugging Face API失败: {response.status_code} - {response.text[:200]}"}
                
        except requests.exceptions.Timeout:
            return {"success": False, "error": "Hugging Face API连接超时，请检查网络连接"}
        except requests.exceptions.ConnectionError:
            return {"success": False, "error": "无法连接到Hugging Face API，请检查网络连接"}
        except Exception as e:
            return {"success": False, "error": f"Hugging Face API异常: {str(e)}"}
    
    def generate_image_with_replicate(self, image_prompt, style):
        """使用Replicate免费API生成图片"""
        try:
            # 使用Replicate的免费Stable Diffusion API
            url = "https://api.replicate.com/v1/predictions"
            
            headers = {
                "Authorization": "Token r8_placeholder",  # 需要实际的token
                "Content-Type": "application/json"
            }
            
            data = {
                "version": "ac732df83cea7fff18b8472768c88ad041fa750ff7682a21affe81863cbe77e4",
                "input": {
                    "prompt": image_prompt,
                    "width": 512,
                    "height": 512,
                    "num_inference_steps": 20
                }
            }
            
            response = requests.post(url, headers=headers, json=data, timeout=30)
            
            if response.status_code == 201:
                # 创建成功，获取结果URL
                result = response.json()
                return {
                    "success": True,
                    "image_url": result.get("urls", {}).get("get")
                }
            else:
                return {"success": False, "error": f"Replicate API失败: {response.status_code}"}
                
        except Exception as e:
            return {"success": False, "error": f"Replicate API异常: {str(e)}"}
    
    def generate_image_with_pollinations(self, image_prompt, style):
        """使用Pollinations免费API生成图片"""
        try:
            # 使用Pollinations的免费API
            # 这个API不需要认证，但有速率限制
            import urllib.parse
            
            # 编码提示词
            encoded_prompt = urllib.parse.quote(image_prompt)
            
            # 构建URL
            url = f"https://image.pollinations.ai/prompt/{encoded_prompt}?width=512&height=512&seed=-1&model=flux&nologo=true"
            
            response = requests.get(url, timeout=30)
            
            if response.status_code == 200:
                # 返回图片数据
                import base64
                image_data = base64.b64encode(response.content).decode('utf-8')
                return {
                    "success": True,
                    "image_data": f"data:image/png;base64,{image_data}"
                }
            else:
                return {"success": False, "error": f"Pollinations API失败: {response.status_code}"}
                
        except Exception as e:
            return {"success": False, "error": f"Pollinations API异常: {str(e)}"}
    
    
    def poll_task_status(self, task_id, headers):
        """轮询任务状态"""
        import time
        
        max_attempts = 30  # 最多轮询30次
        attempt = 0
        
        while attempt < max_attempts:
            try:
                response = requests.get(
                    f'https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}',
                    headers=headers,
                    timeout=30
                )
                
                print(f"轮询状态码: {response.status_code}")
                print(f"轮询响应: {response.text}")
                
                if response.status_code == 200:
                    result = response.json()
                    print(f"轮询结果: {json.dumps(result, ensure_ascii=False, indent=2)}")
                    
                    if 'output' in result:
                        output = result['output']
                        if 'task_status' in output:
                            status = output['task_status']
                            print(f"任务状态: {status}")
                            
                            if status == 'SUCCEEDED':
                                # 任务成功，获取图片URL
                                if 'results' in output and len(output['results']) > 0:
                                    image_url = output['results'][0].get('url')
                                    if image_url:
                                        return {
                                            "success": True,
                                            "image_url": image_url,
                                            "source": "tongyi"
                                        }
                                    else:
                                        return {"success": False, "error": "图片URL为空"}
                                else:
                                    return {"success": False, "error": "没有生成结果"}
                            elif status == 'FAILED':
                                return {"success": False, "error": "任务执行失败"}
                            else:
                                # 任务还在进行中，等待后继续轮询
                                print(f"任务进行中，等待2秒后继续轮询... (尝试 {attempt + 1}/{max_attempts})")
                                time.sleep(2)
                                attempt += 1
                                continue
                        else:
                            return {"success": False, "error": "无法获取任务状态"}
                    else:
                        return {"success": False, "error": "返回格式异常"}
                else:
                    return {"success": False, "error": f"轮询失败: {response.status_code}"}
                    
            except Exception as e:
                return {"success": False, "error": f"轮询异常: {str(e)}"}
        
        return {"success": False, "error": "任务超时"}
    
    def generate_image_placeholder(self, visual_prompt, style):
        """生成图片占位符和指导信息"""
        return {
            "success": True,
            "image_url": None,
            "image_guide": f"""
            <div style="padding: 20px; background: #f8f9ff; border-radius: 10px; margin: 10px 0; border: 2px dashed #ccc;">
                <h4>🎨 图片生成指导</h4>
                <p><strong>场景描述:</strong> {visual_prompt}</p>
                <p><strong>画风:</strong> {style}漫画风格</p>
                <hr>
                <h5>📝 使用以下提示词在AI绘画工具中生成图片:</h5>
                <div style="background: #fff; padding: 10px; border-radius: 5px; font-family: monospace; font-size: 12px; word-break: break-all; border: 1px solid #ddd;">
                    {visual_prompt}, {style}漫画风格, 高质量, 清晰, 动漫风格, 漫画分镜, 1024x1024
                </div>
                <hr>
                <h5>🛠️ 推荐的AI绘画工具:</h5>
                <ul>
                    <li><strong>Pollinations AI:</strong> <a href="https://pollinations.ai" target="_blank">pollinations.ai</a> (免费)</li>
                    <li><strong>Hugging Face Spaces:</strong> <a href="https://huggingface.co/spaces" target="_blank">huggingface.co/spaces</a> (免费)</li>
                    <li><strong>Stable Diffusion WebUI:</strong> 本地部署 (免费)</li>
                    <li><strong>Midjourney:</strong> 付费订阅</li>
                    <li><strong>DALL-E 3:</strong> 通过 ChatGPT Plus 使用</li>
                    <li><strong>通义万相:</strong> 阿里云AI绘画平台</li>
                </ul>
                <hr>
                <h5>🔧 网络问题解决方案:</h5>
                <ul>
                    <li>检查网络连接是否正常</li>
                    <li>尝试使用VPN或代理</li>
                    <li>稍后重试，免费API可能有速率限制</li>
                    <li>考虑使用本地部署的Stable Diffusion</li>
                </ul>
                <p style="color: #666; font-size: 12px;">
                    💡 提示: 将上面的提示词复制到任何AI绘画工具中，即可生成对应的漫画分镜图片。
                </p>
            </div>
            """
        }

# 初始化转换器
converter = NovelToComicConverter()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/analyze', methods=['POST'])
def analyze_novel():
    """
    分析小说文本，提取情节和人物信息
    """
    try:
        data = request.get_json()
        text = data.get('text', '')
        style = data.get('style', '日系')
        target_scene = data.get('target_scene', '通用')
        panel_count = data.get('panel_count', 4)
        # 验证分镜数量在1-12之间
        if not isinstance(panel_count, int) or panel_count < 1 or panel_count > 12:
            return jsonify({
                "success": False,
                "error": "分镜数量必须在1-12之间"
            })
        
        if not text:
            return jsonify({"error": "请输入小说文本"}), 400
        
        # 调用通义千问分析文本
        result = converter.parse_novel_text(text, style, target_scene, panel_count)
        
        if "error" in result:
            return jsonify(result), 500
        
        return jsonify({
            "success": True,
            "analysis": result
        })
        
    except Exception as e:
        return jsonify({"error": f"分析失败: {str(e)}"}), 500

@app.route('/api/panels', methods=['GET'])
def get_panels():
    """
    获取分镜列表
    """
    try:
        # 这里可以从数据库或缓存中获取分镜数据
        # 暂时返回示例数据
        panels = [
            {
                "panel_id": 1,
                "scene": "路边的草地",
                "action": "小狗在草地上玩耍，四处张望",
                "visual_prompt": "一只可爱的小狗在绿色草地上玩耍，阳光明媚"
            },
            {
                "panel_id": 2,
                "scene": "小狗发现了一个小球",
                "action": "小狗看到一个滚动的小球，兴奋地跑过去",
                "visual_prompt": "小狗发现红色小球，眼睛闪闪发光，准备追逐"
            },
            {
                "panel_id": 3,
                "scene": "小狗把小球叼回来",
                "action": "小狗成功把小球叼回给主人",
                "visual_prompt": "小狗叼着小球跑向主人，尾巴摇来摇去"
            }
        ]
        
        return jsonify({
            "success": True,
            "panels": panels
        })
        
    except Exception as e:
        return jsonify({"error": f"获取分镜失败: {str(e)}"}), 500

@app.route('/api/generate', methods=['POST'])
def generate_comic():
    """
    生成漫画
    """
    try:
        data = request.get_json()
        panels = data.get('panels', [])
        style = data.get('style', '日系')
        characters = data.get('characters', [])
        selected_panels = data.get('selected_panels', [])  # 用户选择的分镜
        
        if not panels:
            return jsonify({"error": "没有分镜数据"}), 400
        
        # 如果用户选择了特定分镜，只生成选中的分镜
        if selected_panels:
            panels = [panel for panel in panels if panel.get('panel_id') in selected_panels]
        
        # 构建人物描述
        character_descriptions = ", ".join([f"{char['name']}: {char['description']}" for char in characters])
        
        generated_panels = []
        
        for panel in panels:
            visual_prompt = panel.get('visual_prompt', '')
            panel_id = panel.get('panel_id')
            if not visual_prompt:
                continue
                
            # 生成单格漫画描述
            result = converter.generate_comic_panel(visual_prompt, style, character_descriptions, panel_id)
            
            if result.get('success'):
                panel_data = {
                    "success": True,
                    "panel_id": panel_id,
                    "visual_prompt": result['visual_prompt'],
                    "scene": panel.get('scene', ''),
                    "action": panel.get('action', '')
                }
                
                # 添加图片信息
                if result.get('image_url'):
                    panel_data['image_url'] = result['image_url']
                if result.get('local_url'):
                    panel_data['local_url'] = result['local_url']
                if result.get('filename'):
                    panel_data['filename'] = result['filename']
                if result.get('download_success'):
                    panel_data['download_success'] = result['download_success']
                if result.get('download_error'):
                    panel_data['download_error'] = result['download_error']
                
                generated_panels.append(panel_data)
            else:
                generated_panels.append({
                    "success": False,
                    "panel_id": panel_id,
                    "error": result.get('error', '生成失败'),
                    "visual_prompt": result.get('visual_prompt', ''),
                    "scene": panel.get('scene', ''),
                    "action": panel.get('action', '')
                })
        
        return jsonify({
            "success": True,
            "panels": generated_panels
        })
        
    except Exception as e:
        return jsonify({"error": f"生成失败: {str(e)}"}), 500

@app.route('/api/download/<filename>', methods=['GET'])
def download_image(filename):
    """
    下载生成的图片
    """
    try:
        filepath = os.path.join(IMAGES_DIR, filename)
        if os.path.exists(filepath):
            from flask import send_file
            return send_file(filepath, as_attachment=True, download_name=filename)
        else:
            return jsonify({"error": "文件不存在"}), 404
    except Exception as e:
        return jsonify({"error": f"下载失败: {str(e)}"}), 500

@app.route('/api/images/<filename>', methods=['GET'])
def get_image(filename):
    """
    获取图片文件
    """
    try:
        filepath = os.path.join(IMAGES_DIR, filename)
        if os.path.exists(filepath):
            from flask import send_file
            return send_file(filepath)
        else:
            return jsonify({"error": "文件不存在"}), 404
    except Exception as e:
        return jsonify({"error": f"获取图片失败: {str(e)}"}), 500

@app.route('/api/health', methods=['GET'])
def health_check():
    """
    健康检查接口
    """
    return jsonify({
        "status": "healthy",
        "timestamp": datetime.now().isoformat(),
        "services": {
            "tongyi": "configured" if TONGYI_API_KEY else "missing",
            "tongyi_secret": "configured" if TONGYI_SECRET_KEY else "missing"
        },
        "image_apis": {
            "tongyi_wanx": "configured" if TONGYI_API_KEY else "missing",
            "pollinations": "available",
            "hugging_face": "available",
            "replicate": "available (requires token)"
        }
    })

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
